<template>
    <list-layout>
        <div slot="search">
            <el-form :model="queryParams" :inline="true" ref="queryForm" v-show="showSearch" label-width="88px">
                <el-form-item :label="$t('inventoryManagement.factory')" prop="factoryCode">
                    <el-select v-model="queryParams.factoryCode" :placeholder="$t('public.select_holder',{select_holder: $t('inspectionManagement.plantArea')})" style="width:100%;" filterable clearable size="small">
                        <el-option v-for="(item) in factoryList" :key="item.plantCode" :label="item.plantName" :value="item.plantCode" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('inventoryManagement.inspectionBatchNo')" prop="inspectionLotMark">
                    <el-input v-model="queryParams.inspectionLotMark" :placeholder="
                        $t('public.placeholder', {
                          placeholder: $t('inventoryManagement.inspectionBatchNo'),
                        })
                      " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!-- <el-form-item label="批次" prop="lot">
                    <el-input v-model="queryParams.lot" :placeholder="
              $t('public.placeholder', {
                placeholder: '批次',
              })
            " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item> -->
                <el-form-item :label="$t('inventoryManagement.materialName')" prop="materialName">
                    <el-input v-model="queryParams.materialName" :placeholder="
              $t('public.placeholder', {
                placeholder: $t('inventoryManagement.materialName'),
              })
            " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item :label="$t('inventoryManagement.materialNo')" prop="materialCode">
                    <el-input v-model="queryParams.materialCode" :placeholder="
              $t('public.placeholder', {
                placeholder: $t('inventoryManagement.materialNo'),
              })
            " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!-- <el-form-item :label="$t('inventoryManagement.materialType')" prop="materialType">
                    <el-autocomplete style="width:100%" size="small" popper-class="my-autocomplete" v-model="queryParams.materialType" :fetch-suggestions="materialTypeRemoteMethod" placeholder="请输入内容" @select="(e)=>handleMaterialTypeSelect(e,scope)">
                        <i class="el-icon-search el-input__icon" slot="suffix">
                        </i>
                        <template slot-scope="{ item }">
                            {{ item.typeName }}
                        </template>
                    </el-autocomplete>
                </el-form-item> -->
                <el-form-item :label="$t('inventoryManagement.supplierNo')" prop="supplierCode">
                    <el-input v-model="queryParams.supplierCode" :placeholder="
              $t('public.placeholder', {
                placeholder: $t('inventoryManagement.supplierNo'),
              })
            " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
            </el-form>
            <div style="display: flex; justify-content: center">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("public.search") }}</el-button>
                <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{
          $t("public.reset")
        }}</el-button>
            </div>
        </div>
        <div class="app-container">
            <div class="container-header">
                <div class="header-left">
                    {{ $t("inventoryManagement.inventoryInspection") }}
                </div>
            </div>
            <el-row :gutter="10" class="mb8 btnGroup">
                <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ny-iqc:repertory:add']">{{ $t("inventoryManagement.createdInspection") }}</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button size="mini" class="exportitemBtn" @click="handleExport" v-hasPermi="['ny-iqc:repertory:export']"><img src="@/assets/images/icons/daochu.png" alt="" />
                        {{ $t("public.export") }}</el-button>
                </el-col>
                <!--                <el-col :span="1.5">
                    <el-button size="mini" class="importitemBtn" v-hasPermi="['ny-iqc:repertory:sendSAP']" @click="checkout">SAP</el-button>
                </el-col>-->
            </el-row>

            <div class="container-table">
                <el-table :height="tableHeight" :row-class-name="tableRowClassName" border v-loading="loading" :data="repertoryList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" fixed="left" />
                    <!-- <el-table-column :label="$t('inventoryManagement.supplierBatchNo')" align="left" prop="lichn" minWidth="160" /> -->
                    <!-- <el-table-column :label="$t('inventoryManagement.batch')" align="left" minWidth="160" prop="lot" :show-overflow-tooltip="true" /> -->
                    <el-table-column :label="$t('inventoryManagement.materialNo')" minWidth="160" prop="materialCode" align="left" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('inventoryManagement.materialName')" minWidth="200" align="left" prop="materialName" :show-overflow-tooltip="true" />
                    <!-- <el-table-column label="MSL等级" sortable align="left" minWidth="100" prop="materialMsl" :show-overflow-tooltip="true" /> -->
                    <!-- <el-table-column label="规格型号" sortable align="left" prop="specificationsModels" min-width="160" :show-overflow-tooltip="true" /> -->
                    <el-table-column :label="$t('inventoryManagement.factory')" minWidth="180" align="left" prop="factoryName" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('inventoryManagement.materialDocument')" minWidth="120" align="left" prop="mblnr" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('inventoryManagement.inventoryQuantity')" align="left" prop="quantityAmount" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('inventoryManagement.unit')" align="center" prop="mengeneinh" minWidth="100" />
                    <!--                    <el-table-column :label="$t('inventoryManagement.supplierName')" align="left" prop="supplierName" minWidth="120" :show-overflow-tooltip="true" />-->
                    <el-table-column :label="$t('inventoryManagement.supplierNo')" align="left" prop="supplierCode" minWidth="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('inventoryManagement.inspectionBatchNo')" align="left" prop="inspectionLotMark" minWidth="160" :show-overflow-tooltip="true" />

                    <el-table-column :label="$t('inventoryManagement.useDecision')" align="left" prop="usingDecision" />
                    <!-- <el-table-column :label="$t('inventoryManagement.approvalTime')" align="left" prop="approveTime" minWidth="160" :show-overflow-tooltip="true" /> -->
                    <el-table-column :label="$t('inventoryManagement.endDate')" align="left" prop="expireDate" minWidth="160" :show-overflow-tooltip="true" />

                    <el-table-column :label="$t('inspectionManagement.isIncoming')" align="left" minWidth="120" prop="release" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <span class="labelY" v-if="parseInt(scope.row.isIncomingInspection) > 0">是</span>
                                <span class="labelN" v-if="parseInt(scope.row.isIncomingInspection) === 0">否</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('public.createTime')" align="left" prop="createTime" minWidth="160" :show-overflow-tooltip="true" />
                    <!--                    <el-table-column :label="$t('public.remark')" align="center" prop="extraRemark" minWidth="160" :show-overflow-tooltip="true" />-->
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <table-body-btn type="gwview" :name="$t('home.view')" v-hasPermi="['masterdata:supplier:edit']" @click.native="handleView(scope.row)" />
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>

            <!-- 新增 -->
            <el-dialog title="新增" :visible.sync="addInspectionExemption" center top="24vh" width="800px" append-to-body :fullscreen="fullscreen">
                <el-form :model="addModel" :rules="rules" ref="addForm" label-width="145px">
                    <el-row :gutter="24" class="mb8">
                        <el-col :span="12">
                            <el-form-item :label="$t('inventoryManagement.materialName')" prop="materialName">
                                <el-input v-model="addModel.materialName" clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="$t('inventoryManagement.materialNo')" prop="materialNo">
                                <el-input v-model="addModel.materialNo" clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="$t('inventoryManagement.supplierNo')" prop="supplierNo">
                                <el-input v-model="addModel.supplierNo" clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item :label="$t('inventoryManagement.inspectionExemptionReason')" prop="inspectionExemptionReason">
                                <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" :placeholder="
                    $t('public.placeholder', {
                      placeholder: $t(
                        'inventoryManagement.inspectionExemptionReason'
                      ),
                    })
                  " v-model="addModel.inspectionExemptionReason" maxlength="1000">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item :label="$t('inventoryManagement.uploadAttachments')" prop="uploadAttachments">
                                <file-upload-input v-model="addModel.file" @change="fileChange"></file-upload-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitForm" icon="el-icon-check" size="small">{{ $t("public.save") }}</el-button>
                </div>
            </el-dialog>

        </div>
    </list-layout>
</template>

<script>
import {getType, refreshCache} from '@/api/basic/dict/type'

import {checkout, repertoryList,} from '@/api/inspectionManagement/inspectionManagement'
import {addCheckValied, proofread, updateValidityDate,} from '@/api/inventoryManagement/inspectedInventory'

import {listMaterialType} from '@/api/basic/materialtype'
import FileUploadInput from '@/components/FileUploadInput'
import {mapState} from 'vuex'
import {listAllFactory} from '@/api/basic/factory'

export default {
    name: 'inspectionExemption',
    dicts: ['sys_normal_disable', 'NYIQC_NCR_DECISION'],
    components: {
        FileUploadInput,
    },
    computed: {
        ...mapState({
            isFold: (state) => state.app.isFold,
        }),
    },
    watch: {
        isFold(val) {
            if (val === true) {
                this.tableHeight = 'calc(100vh - 308px)'
            } else {
                this.tableHeight = 'calc(100vh - 426px)'
            }
        },
    },
    data() {
        return {
            factoryList: [],
            direction: 'rtl',
            templateVisible: false,
            addInspectionExemption: false,
            drawer: false,
            approvalOpen: false,
            viewInspectionExemption: false,
            tableHeight: 'calc(100vh - 308px)',
            addModel: {},
            viewModel: {
                materialName: '',
                materialNo: '',
                supplierNo: '',
                inspectionExemptionReason: '',
            },
            editModel: {},
            approvalForm: {
                status: '1',
                textarea: '',
            },
            selBtn: 1,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 字典表格数据
            repertoryList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            selectRows: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                inspectionLotMark: null,
                lot: '',
                materialName: '',
                materialCode: '',
                status: '',
                supplierCode: '',
                materialType: undefined,
            },
            // 表单参数
            form: {},
            inspecStatus: [
                { label: '全部', value: '0' },
                { label: '待校对', value: '1' },
                { label: '待审批', value: '2' },
                { label: '审批通过', value: '3' },
                { label: '审批不通过', value: '4' },
            ],
            // 表单校验
            rules: {
                materialName: [
                    {
                        required: true,
                        message: this.$t('formValidation.materialNameCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                materialNo: [
                    {
                        required: true,
                        message: '物料编号不能为空',
                        trigger: 'blur',
                    },
                ],
                supplierNo: [
                    {
                        required: true,
                        message: '供应商编号不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            fullscreen: false,
        }
    },
    mounted() {
        if (this.$route.query.status) {
            this.queryParams.isIncomingInspection = this.$route.query.status
        }
        this.getList()
        this.getFactoryList()
    },
    methods: {
        getFactoryList() {
            listAllFactory().then((res) => {
                this.factoryList = res.data
            })
        },
        materialTypeRemoteMethod(val, cb) {
            listMaterialType({ typeName: val }).then((res) => {
                cb(res.rows)
            })
        },
        handleMaterialTypeSelect(e, scope) {
            // this.dialogForm.materialType = e
            this.queryParams.materialType = e.typeName
            this.$forceUpdate()
        },
        checkout() {
            if (this.selectRows.length !== 1) {
                this.$modal.msgWarning('请选择一个库存检验单!')
                return
            }
            checkout({
                id: this.selectRows[0].id,
            }).then((res) => {
                this.getList()
            })
        },
        usingDecisionFilter(row) {
            if (row.usingDecision) {
                let io = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                    return item.value == row.usingDecision
                })
                return io.label
            } else return ''
        },
        statusfilter(row) {
            if (!row.status) {
                return ''
            } else {
                let row = this.inspecStatus.filter((item) => {
                    return item.value === row.status
                })
                return row.label
            }
        },
        effectDateChange(e, scope) {
            updateValidityDate({ id: scope.row.id, vfdat: e }).then(
                (response) => {
                    this.getList()
                    // if(parseInt(e)>0 &&scope.row.approveTime){
                    //         this.repertoryList[scope.$index].endDate = this.getNewDay(scope.row.approveTime, e)
                    // }
                }
            )
        },
        getNewDay(dateTemp, days) {
            var nDate = new Date(dateTemp)
            var millSeconds = Math.abs(nDate) + days * 24 * 60 * 60 * 1000
            var rDate = new Date(millSeconds)
            var year = rDate.getFullYear()
            var month = rDate.getMonth() + 1
            //时 getHours()：(0 ~ 23)
            var hour = rDate.getHours()
            //分 getMinutes()： (0 ~ 59)
            var minute = rDate.getMinutes()
            //秒 getSeconds()：(0 ~ 59)
            var second = rDate.getSeconds()
            if (month < 10) month = '0' + month
            var date = rDate.getDate()
            if (date < 10) date = '0' + date
            return (
                year +
                '-' +
                month +
                '-' +
                date +
                ' ' +
                hour +
                ':' +
                minute +
                ':' +
                second
            )
        },
        fileChange(e) {
            console.log(e)
        },
        drawerClose() {
            this.drawer = false
        },
        /** 查询字典类型列表 */
        getList() {
            this.loading = true
            repertoryList(this.queryParams).then((response) => {
                if (response.code == 200 && response.rows) {
                    this.repertoryList = response.rows
                    this.total = response.total
                    this.loading = false
                    this.tableHeight = this.isFold
                        ? 'calc(100vh - 308px)'
                        : 'calc(100vh - 466px)'
                }
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }

            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.isIncomingInspection = null
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning('请至少选择一条库存检验单!')
                return
            }
            addCheckValied({ id: this.ids[0] }).then((res) => {
                if (res.code === 200) {
                    this.$router.push({
                        path: '/inventoryInspection/add/index/' + this.ids[0],
                    })
                }
            })
        },
        tableRowClassName({ row, rowIndex }) {
            console.log('rowIndex', rowIndex, row)
            if (row.isHighLight === true) {
                console.log('rowIndex', row)
                return 'rowHighLight' //若isHighLight为true，则使用“rowHighLight”样式
            } else {
                return ''
            }
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selectRows = selection
            this.ids = selection.map((item) => item.id)
            this.selectRows = selection
            this.single = selection.length != 1
            this.repertoryList.forEach((io, index) => {
                console.log('includes', this.ids.includes(io.id))
                if (this.ids.includes(io.id)) {
                    io.isHighLight = true
                } else {
                    io.isHighLight = false
                }
            })
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const dictId = row.dictId || this.ids
            getType(dictId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '修改字典类型'
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['addForm'].validate((valid) => {
                if (valid) {
                    this.$modal.msgSuccess('提交成功!')
                    this.addInspectionExemption = false
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        /** 发起检验提交 */
        submitAddForm: function () {
            this.$modal.msgSuccess('发起成功!')
            this.addInspection = false
        },

        /** 删除按钮操作 */
        handleComplete(row) {
            if (this.ids.length === 0) {
                this.$modal.msgWarning('请至少选择一条库存检验单!')
                return
            }
            this.$modal.confirm('是否确认完成校对？').then(() => {
                proofread({ ids: this.ids.join(',') }).then(() => {
                    this.$modal.msgSuccess('校对成功!')
                })
            })
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.$router.push({
                path: '/inventoryInspection/detail/index/' + row.id,
                query: {
                    isView: 1,
                },
            })
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.drawer = true
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            this.drawer = false
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                '/ny-iqc/repertory/export',
                {
                    ...this.queryParams,
                },
                `type_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    float: left;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 40px;
    display: flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.header-right {
    float: right;
}
.container-header {
    float: left;
    width: 100%;
    border-bottom: 1px solid #ededf2;
}
.container-table {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}
::v-deep .rowHighLight {
    background: oldlace;
}
</style>
